#! /bin/sh
#
# svnx <command> [path-or-URL]


function fullPath ()
{
	local d="${1:-.}"
	if [ -e "$d" ]; then
		echo `cd -L $(dirname -- "$d") && pwd`/"${d##*/}"
	else
		echo "$d"
	fi
}

function doFn ()	# fn arg
{
	osascript -e "on run args
		tell app \"svnX\"
			activate
			$1 args
		end
	end" "`fullPath \"$2\"`"
}

function openLogWindow ()	# <file-path>
{
	if [ -e "${1:?}" ]; then
		doFn 'displayHistory' "`fullPath \"$1\"`"
	fi
}

function openWCWindow ()	# [working-copy-path]
{
	f="`fullPath \"$1\"`"
	if [ ! -d "$f" ]; then f=`dirname "$f"`; fi
	if [ -d "$f" ]; then doFn 'openWorkingCopy' "$f"; fi
}

function openRepoWindow ()	# [wc-path-or-URL]
{
	f="$1"
	if [ "$f" == "${f#[a-9]:}" ]; then
		f=`fullPath "$f"`
		if [ ! -e "$f" ]; then return 1; fi
		if [ -f "$f" ]; then f=`dirname "$f"`; fi
		f=`svn info "$f" | grep 'URL:' | cut -d ' ' -f2`
	fi
	doFn 'openRepository' "$f"
}

function diffFiles ()	# files...
{
	for f; {
		osascript -e 'on run args' -e 'tell app "svnX" to diffFiles args' -e 'end' "`fullPath \"$f\"`"
	}
}

function openFiles ()	# files...
{
	for f; {
		osascript -e 'on run args' -e 'tell app "svnX" to openFiles args' -e 'end' "`fullPath \"$f\"`"
	}
}

function resolveFiles ()	# files...
{
	for f; {
		osascript -e 'on run args' -e 'tell app "svnX" to resolveFiles args' -e 'end' "`fullPath \"$f\"`"
	}
}

function usage ()
{
	echo 'svnx <command> [path-or-URL]   - the svnX command line tool.'
	echo '     help                      - display this usage text.'
	echo '     log|-l <file-path>        - open log sheet for file-path.'
	echo '     wc|-w [working-copy-path] - open window for working-copy-path (defaults to ".").'
	echo '     rep|-r [wc-path-or-URL]   - open repository window for wc-path-or-URL (defaults to ".").'
	echo '     diff|-d <file-path...>    - compare the files with their base revisions.'
	echo '     open|-o <file-path...>    - open the files and/or folders in appropriate applications.'
	echo '     resolve|-v <file-path...> - interactively resolve conflicted files.'
}


#echo "SVNX <$1>"

case "$1" in
	log|-l)			openLogWindow "$2";;
	wc|-w)			openWCWindow "$2";;
	rep|-r)			openRepoWindow "$2";;
	diff|-d)		shift; diffFiles "$@";;
	open|-o)		shift; openFiles "$@";;
	resolve|-v)		shift; resolveFiles "$@";;
	help|*)			usage;;
esac

